let utils = require("../../../utils/util.js");
let tcity = require("../../../utils/cityData.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    maskCondition: false,
    wxOpenId: "",
    wxNickName: "",
    headImgSrcType: 1,
    headImgSrc: "/imgs/icon-userhead-placeholder.png",
    wxGender: 1,
    mobile: "",
    allShopTypes: [
      { "id": 1, "name": "企业" },
      { "id": 2, "name": "个人" }
    ],
    shopTypePickerIndex: 0,
    shopTypeName: "请选择店铺类型",
    provinces: [],
    citys: [],
    countys: [],
    value: [0, 0, 0],
    values: [0, 0, 0],
    locationId: 0,//选择的城市ID
    locationName: "请选择所在地区",
    condition: false,
    mapLocationName: "",
    mapLocationAddress: "",
    mpaLatitude: 0,
    mapLongitude: 0,
    finalAddress:'',
    shopImgFullPaths: [],
    headImg: {
      FileHttpFullPath: "",
      FileRelativeFullPath: ""
    },
    shopInfo:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.getMyShop(options.shopid);
 
   
    console.log('初始化完成');
  },
  /**
   * 获取我的店铺信息
   */
  getMyShop: function (shopid) {
    var that = this;
    var shopImg=[];
    utils.getData(
      utils.apiUrl + "/shop/GetShopDetail?shopId=" + shopid,
      {},
      function (response) {
        var index = 0;
        for (let i = 0; i < that.data.allShopTypes.length;i++)
        {
          if (that.data.allShopTypes[i].id == response.data.ShopTypeId)
          {
            index=i;
          }
        }
        for (let i = 0; i < response.data.ShopImgs.length;i++)
        {
          var imgArr = { 'FileHttpFullPath': response.data.ShopImgs[i].HttpImgUrl, 'FileRelativeFullPath': response.data.ShopImgs[i].ImgUrl, 'ImageId': response.data.ShopImgs[i].Id,'IsUp':1}
          shopImg.push(imgArr);
        }
        that.setData({
          shopInfo: response.data,
          shopTypeName: response.data.ShopTypeName,
          shopTypePickerIndex: index,
          locationName: response.data.CityName,
          shopImgFullPaths: shopImg,
          headImg: response.data.HeadImgSrcArr,
          headImgSrc: response.data.HeadImgSrcArr[0],
          headImgSrcType: response.data.HeadImgSrcType,
          locationId: response.data.CountyId,
          mapLocationName: response.data.MapLocationName,
          mapLocationAddress: response.data.MapLocationAddress,
          finalAddress: response.data.Address,
          mapLatitude: response.data.MapLatitude,
          mapLongitude: response.data.MapLogitude
        });
        that.bindCityPicker(response)
      }
    );
  },
  /**
   * 初始化城市信息
   */
  bindCityPicker:function(response)
  {
    var that = this;
    //tcity.init(that);
    //var cityData = that.data.cityData;
    const provinces = tcity.provinceList();
    provinces.splice(0, 1);
    const citys = tcity.cityList(response.data.ProvinceId);
    citys.splice(0, 1);
    const countys = tcity.countyList(response.data.ProvinceId, response.data.CityId);
    countys.splice(0, 1);
    const arr=[];
    for (let i = 0; i < provinces.length; i++) {
      if (provinces[i].value == response.data.ProvinceId)
       {
         arr.push(i);
         for (let j = 0; j < citys.length;j++) {
           if (citys[j].value == response.data.CityId) {
             arr.push(j);
             for (let k = 0; k < countys.length; k++) {
               if (countys[k].value == response.data.CountyId) {
                 arr.push(k);
               }
             }
           }
         }
       }
     }
    that.setData({
      'provinces': provinces,
      'citys': citys,
      'countys': countys,
      'value': arr,
      'values': arr
    })
  },
  /**
   * 跳转修改手机号
   */
  bindChangeMobile:function(){
    wx.navigateTo({
      url: '../modifymobile/modifymobile',
    })
  },
  /**
   * 绑定手机号
   */
  bindMobileInput: function (e) {
    this.setData({
      mobile: e.detail.value
    });
  },
  
/**
 * 店铺类型
 */
  bindShopTypePickerChange: function (e) {
    var index = e.detail.value;
    var name = this.data.allShopTypes[index].name;
    this.setData({
      shopTypePickerIndex: index,
      shopTypeName: name
    })
  },
/**
 * 打开城市区域选择
 */
  bindOpenLocationPicker: function () {
    this.setData({
      condition: true,
      maskCondition: true
    })
  },
  /**
   * 选择地区
   */
  bindLocationPickerConfirm: function () {
    var that = this;
    var val = that.data.value;
    var provinces = that.data.provinces;
    var citys = that.data.citys;
    var countys = that.data.countys;

    var szProvinceName = provinces[val[0]].text;
    var szCityName = citys[val[1]] != null ? citys[val[1]].text : "";
    var szCountyName = countys[val[2]] != null ? countys[val[2]].text : "";
    var szLocationName = szProvinceName + "-" + szCityName + "-" + szCountyName;
    var locationId = countys[val[2]] != null ? countys[val[2]].value : 0;

    this.setData({
      condition: false,
      maskCondition: false,
      locationName: szLocationName,
      locationId: locationId

    });

  },
  /**
   * 关闭地区选择
   */
  bindLocationPickerCancel: function () {
    this.setData({
      condition: false,
      maskCondition: false,
    })
  },
  /**
   * 
   */
  bindLocationChange: function (e) {

    var val = e.detail.value
    var t = this.data.values;
    console.log(val);
    console.log(t);
    //var cityData = this.data.cityData;

    if (val[0] != t[0]) {
      console.log('province no ');
      var s = this.data.provinces;
      const citys = tcity.cityList(s[val[0]].value);
      citys.splice(0, 1);

      const countys = tcity.countyList(s[val[0]].value,citys[0].value);
      countys.splice(0, 1);
      // for (let i = 0; i < cityData[val[0]].childs.length; i++) {
      //   citys.push(cityData[val[0]].childs[i])
      // }
      // if (cityData[val[0]].childs.length > 0 && cityData[val[0]].childs[0].childs) {
      //   for (let i = 0; i < cityData[val[0]].childs[0].childs.length; i++) {
      //     countys.push(cityData[val[0]].childs[0].childs[i])
      //   }
     // }
      this.setData({
        citys: citys,
        countys: countys,
        values: val,
        value: [val[0], 0, 0]
      })
      return;
    }
    if (val[1] != t[1]) {
      console.log('city no');
      var s = this.data.provinces;
      var c = this.data.citys;
      const countys = tcity.countyList(s[val[0]].value, c[val[1]].value);
      countys.splice(0, 1);
      // for (let i = 0; i < cityData[val[0]].childs[val[1]].childs.length; i++) {
      //   countys.push(cityData[val[0]].childs[val[1]].childs[i])
      // }
      this.setData({
        countys: countys,
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      console.log('county no');
      this.setData({
        values: val,
        value: [val[0], val[1], val[2]]
      })
      return;
    }
  },
  bindChooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      type: 'gcj02',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var name = res.name || ''
        var address = res.address || ''
       // that.shopInfo.MapLocationName
        var obj = that.data.shopInfo
        obj.MapLocationAddress = address
        //that.shopInfo.MapLatitude
        //that.shopInfo.MapLogitude
        that.setData({
          shopInfo: obj,
          mapLocationName: name,
          mapLocationAddress: address,
          finalAddress:address,
          mapLatitude: latitude,
          mapLongitude: longitude
        });
      }
    });
  },
  /**
   * 上传头像
   */
  bindChooseHeadImg: function () {
    var that = this;
    var count = 1;
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: utils.apiUrl + '/shop/UpdateUserHeadImage',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            shopId: that.data.shopInfo.ShopID
          },
          success: function (res) {
            var data = JSON.parse(res.data);
            data = JSON.parse(data);

            //do something
            that.setData({
              headImg: data,
              headImgSrc: data.FileHttpFullPath,
              headImgSrcType: 2
            });
          }
        })
      }
    })
  },
  /**
   * 上传店铺图片
   */
  bindChooseImg: function () {
    var that = this;
    var count = 5 - this.data.shopImgFullPaths.length;
    if(count<=0)
    {
      wx.showToast({
        title: '最多上传5张',
        icon: 'none'
      })
      return;
    }
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        for (let i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: utils.apiUrl + '/common/upload',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {

            },
            success: function (res) {
              var data = JSON.parse(res.data);
              data = JSON.parse(data);
              var shopImgFullPaths = that.data.shopImgFullPaths;
              var imgArr = { 'FileHttpFullPath': data.FileHttpFullPath, 'FileRelativeFullPath': data.FileRelativeFullPath, 'ImageId': shopImgFullPaths.length, 'IsUp': 0 }
              shopImgFullPaths.push(imgArr);
              //do something
              that.setData({
                shopImgFullPaths: shopImgFullPaths
              });
            }
          })
        }
      },
      fail: function (e) {
        // wx.showToast({
        //   title: '上传图片失败',
        //   icon: 'none'
        // })
      }
    })
  },
  bindMaskClick: function () {
    this.setData({
      maskCondition: false,
      condition: false
    });
  },
  /**
   * 提交修改内容
   */
  bindFormSubmit: function (e) {
    var that = this;
    console.log(e);
    var formData = e.detail.value;
    if (that.data.headImgSrc == '') {
      wx.showToast({
        title: '请上传头像',
        icon: 'none'
      });
    }
    if (formData.UserName == '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }    
    if (formData.ShopName == '') {
      wx.showToast({
        title: '请输入店铺名称',
        icon: 'none'
      });
      return;
    }
    var dataShopType = that.data.allShopTypes[formData.ShopType].id;
    if (dataShopType<1) {
      wx.showToast({
        title: '请选择店铺类型',
        icon: 'none'
      });
      return;
    }
    if (that.data.locationId == 0) {
      wx.showToast({
        title: '请选择地区',
        icon: 'none'
      });
    }
    if (formData.Address == '') {
      wx.showToast({
        title: '请输入店铺地址',
        icon: 'none'
      });
      return;
    }
    if (formData.Description.replace(/\s+/g, '') == '') {
      wx.showToast({
        title: '请输入公司简介',
        icon: 'none'
      });
      return;
    }
    //build form data
    var headImgSrc = that.data.headImg.FileRelativeFullPath;
    var shopImgs = that.data.shopImgFullPaths.map(item => {
      return item.FileRelativeFullPath
    });
    if (shopImgs.length==0) {
      wx.showToast({
        title: '请上传店铺展示图片',
        icon: 'none'
      });
      return;
    }
    if (shopImgs.length < 2) {
      wx.showToast({
        title: '请至少上传2张店铺展示图片',
        icon: 'none'
      });
      return;
    }
    var shopTypeId = that.data.allShopTypes[formData.ShopType].id;
    formData.ShopType = shopTypeId;
    formData.UserName = formData.UserName;
    formData.ShopName = formData.ShopName;
    formData.LocationId = that.data.locationId;
    formData.MapLocationName = that.data.mapLocationName;
    formData.MapLocationAddress = that.data.mapLocationAddress;
    formData.MapLatitude = that.data.mapLatitude;
    formData.MapLogitude = that.data.mapLongitude;
    formData.ShopImgs = shopImgs;
    formData.Description = formData.Description;
    //console.log('正在提交')
    wx.showLoading({
      title: '正在提交,请等待..',
    });
    utils.postData(
      utils.apiUrl + '/shop/UpdateShop',
      formData,
      function (response) {
        var data = response.data;
        if (response.status == 0) {
          var userId = data.ShopID;
          utils.setUserId(userId);
          wx.switchTab({
            url: '../../my/my',
          });
        }
        else {
          wx.showModal({
            title: '更新失败',
            content: data.message,
            showCancel: false,
          });
        }
      },
      {},
      function () {
        wx.hideLoading();
      }
    )    
    return;
  },

  bindFormReset: function () {

  },
  delChooseImg:function(e){
    var that = this;
    var imgId = e.currentTarget.id;
    var isUp = e.target.dataset.up;
    var imgPath = e.target.dataset.imgpath;
    var index = e.currentTarget.dataset.index;
    console.log('imgId' + imgId)
    var shopImgFullPaths = this.data.shopImgFullPaths;
    if (shopImgFullPaths.length > 0) {
      shopImgFullPaths.splice(index, 1);
      this.setData({
        shopImgFullPaths: shopImgFullPaths
      });
    }
      // var k = 0;
      // var shopImg = [];
      // for (let i = 0; i < that.data.shopImgFullPaths.length; i++) {
      //   if (that.data.shopImgFullPaths[i].FileHttpFullPath != imgPath) {
      //     shopImg.push(that.data.shopImgFullPaths[i]);
      //   }
      // }
      that.setData({
        shopImgFullPaths: shopImg
      });
      return;
  
  },
  /**
   * 删除店铺图片后数组中也要删除
   */
  sortChooseImg: function (imgId){
    var that = this;
    var k = 0;
    var shopImg = [];
    for (let i = 0; i < that.data.shopImgFullPaths.length; i++) {
      if (that.data.shopImgFullPaths[i].ImageId != imgId) {
        shopImg.push(that.data.shopImgFullPaths[i]);
      }
    }
    that.setData({
      shopImgFullPaths: shopImg
    });
  }

})